package com.zs4sdk.activity;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.ipaynow.plugin.api.IpaynowPlugin;
import com.ipaynow.plugin.manager.route.dto.ResponseParams;
import com.ipaynow.plugin.manager.route.impl.ReceivePayResult;
import com.ipaynow.plugin.utils.PreSignMessageUtil;
import com.ipaynow.plugin.view.IpaynowLoading;
import com.zs4sdk.Zs4GameBase;
import com.zs4sdk.Zs4GameMenu;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonEventHandler.ResultHandlerInEvent;
import com.common.library.data.CommonHandle;
import com.common.library.data.CommonHandle.HandleMessage;
import com.common.library.data.EventHandler2Post;
import com.zs4sdk.dialog.XZPayLoading;
import com.zs4sdk.entity.XZOrderResultEntity;
import com.zs4sdk.entity.XzSignOrderResultEntity;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.entity.OrderResultEntity;
import com.zs4sdk.extra.Zs4GameCode;
import com.zs4sdk.jslocalobj.Zs4GamePaymentInJavascriptLocalObj;
import com.zs4sdk.jslocalobj.Zs4GamePaymentInJavascriptLocalObj.zs4gamePaymentInJavascriptCallback;
import com.common.library.util.ActivityHelper;
import com.common.library.util.CommonWebChromeClient;
import com.common.library.util.DialogUtils;
import com.common.library.util.EncryptHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.LogUtil;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.common.library.util.ProjectHelper;

/**
 * function: 充值
 *
 * @ author: aXiBa
 */
public class Zs4GameVoucherActivity extends Zs4GameBaseWebActivity implements ReceivePayResult {

    private static final String TAG = Zs4GameVoucherActivity.class.getSimpleName();

    private static final int FLAG_REQUESTORDERID_SECURE = 1;
    private static final int FLAG_REQUESTORDERID_SKYPAY = 5;
    private static final int FLAG_REQUESTORDERID_PPCREDIT = 6;

    public static final String SKYPAY_PAYTPE = "10";

    public static final int SKYPAY_INIT_FINISH = 10004;
    public static final int SKYPAY_BILL_FINISH = 10005;
    public static final int PPCREDIT_INIT_FINISH = 10008;
    public static final int PPCREDIT_BILL_FINISH = 10009;

    private String backSendMsg = Extra.BOOLEAN_FALSE;

    // 返回给webview的支付结果
    private static final String PAYRESULT_WEBVIEW_SUCCESS = "1";
    private static final String PAYRESULT_WEBVIEW_FAIL = "2";


    private IpaynowPlugin mIpaynowplugin;
    private IpaynowLoading mLoadingDialog;
    private PreSignMessageUtil mPreSign = new PreSignMessageUtil();

    private final static int MY_PERMISSIONS_REQUEST_CALL_PHONE = 101;

    private static String XZPAY_WXPAY = "13";
    private static String XZPAY_QQPAY = "25";
    private static String XZPAY_ALIPAY = "12";

    public ProgressDialog mProgress = null;

    DialogUtils dialog;


    // 网页支付：商品id
    private String pay_goods_id = "";
    private String pay_cp_order_id = "";
    private String pay_type = "";
    private String PAY_URL = "";


    private static String pcOrderId = "";

    private final String wxpayURL = "";

    private DialogUtils dialogUtils;

    private int goodmultiple = 1;
    private int goodPrice = 1;

    private void getParams() {

        Intent intent = getIntent();
        if (Helper.isNotNull(intent)) {
            if (intent.hasExtra(Zs4GameBase.KEY_GOODS_ID)) {
                pay_goods_id = intent.getStringExtra(Zs4GameBase.KEY_GOODS_ID);
            }
            if (intent.hasExtra(Zs4GameBase.KEY_CP_ORDER_ID)) {
                pay_cp_order_id = intent.getStringExtra(Zs4GameBase.KEY_CP_ORDER_ID);
            }
            if (intent.hasExtra(Extra.INTENTKEY.INTENT_TYPE)) {
                pay_type = intent.getStringExtra(Extra.INTENTKEY.INTENT_TYPE);
            }
            if (intent.hasExtra(Extra.INTENTKEY.BACKSENDMESSAGE)) {
                backSendMsg = intent.getStringExtra(Extra.INTENTKEY.BACKSENDMESSAGE);
            }
            if (intent.hasExtra(Extra.INTENTKEY.GOOD_PRICE)) {
                goodPrice = Integer.parseInt(intent.getStringExtra(Extra.INTENTKEY.GOOD_PRICE));
            }
            if (intent.hasExtra(Extra.INTENTKEY.GOOD_COUNT)) {
                goodmultiple = Integer.parseInt(intent.getStringExtra(Extra.INTENTKEY.GOOD_COUNT));
            }
            Bundle bundle = intent.getExtras();
            if (Helper.isNotNull(bundle)) {
                if (bundle.containsKey(Extra.INTENTKEY.BACKSENDMESSAGE)) {
                    backSendMsg = bundle.getString(Extra.INTENTKEY.BACKSENDMESSAGE);
                }
            }
//            LogUtil.e("=========1", "pay_typepay_typepay_type:" + pay_type);

            if (pay_type.equals(Extra.INTENTKEY.GAME_TPYE)) {
                PAY_URL = Extra.URL.VOUCHER_API;
               // PAY_URL = "http://sdk.a.zs4gamegame.com//pay.php";
            } else {
            }
//            LogUtil.e("=========2", "pay_typepay_typepay_type:" + pay_type);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_payment"));
        getParams();

        //现在支付初始化
        mIpaynowplugin = IpaynowPlugin.getInstance().init(this);// 1.插件初始化
        mIpaynowplugin.unCkeckEnvironment();// 无论微信、qq安装与否，网关页面都显示渠道按钮。

        this.init();
        mLoadingDialog = new XZPayLoading(mIpaynowplugin.getDefaultLoading());

    }

    @Override
    protected void init() {
        super.init();
        this.getWebView().getSettings().setJavaScriptEnabled(true);
        getWebView().setWebViewClient(createWebViewClient());
        this.getWebView().setWebChromeClient(new CommonWebChromeClient(this) {
            /**
             * Notify the host application of a change in the document title.
             *
             * @param view  The WebView that initiated the callback.
             * @param title A String containing the new title of the document.
             */
            @Override
            public void onReceivedTitle(WebView view, String title) {
                setTopTitle(title);
                super.onReceivedTitle(view, title);
            }
        });

        this.getWebView().addJavascriptInterface(
                new Zs4GamePaymentInJavascriptLocalObj(
                        new zs4gamePaymentInJavascriptCallback() {

                            // 游戏币快捷支付
                            @Override
                            public void onpay(final String param_goodsid) {
                                LogUtil.e("param_goodsid", param_goodsid + "");
                                pay_type = Extra.INTENTKEY.GAME_TPYE;
                                HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.REQUEST_ORDERINFO, FLAG_REQUESTORDERID_SECURE, param_goodsid);
                            }

                            // 网页支付完成处理
                            @Override
                            public void onpaywapcomplete(String orderid) {
//								LogUtil.e("orderid",orderid+"");
                                sendPayCompleteBroadcast(orderid, Zs4GameCode.PAYTYPE_WAP);
                            }

                            //
                            @Override
                            public void goupdateaccount() {
                                Zs4GameMenu.enterAccountCenter(Zs4GameVoucherActivity.this, flag, Zs4GameBase.getPackageName());
                                finish();
                            }

                            @Override
                            public void revoucher() {
                                HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.GOTO_VOUCHER_AGAIN);
                            }

                            @Override
                            public void goto_game() {
                                LogUtil.e("回到游戏...", flag);
                                backToGame();
                            }
                        }), "nsdk_obj");
        this.getWebView().getSettings()
                .setJavaScriptCanOpenWindowsAutomatically(true);


        if (!NetworkHelper.isNetworkAvailable(this)) {
            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        } else {
            this.loadVoucher();
        }
    }


    /**
     * function: 载入充值页
     *
     * @ author: aXiBa 2014-1-8 下午4:57:47
     */
    private void loadVoucher() {
//		LogUtil.e("加载支付页面",".......1");

        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWPROCESS_CANCANCEL);
        // 发送请求
        String url = String.format("%s?v=%s&timestamp=%s&app_id=%d&goodid=%s",
                PAY_URL,
                Extra.VERSION_API,
                getTimestamp(),
                Zs4GameData.getInstance().getAppId(),
                pay_goods_id);
        String ua = String.format("payamount=%s&goodmultiple=%s&app_id=%d&area_server_id=%s&role_name=%s" +
                "&role_id=%s&area_server_name=%s&user_id=%s&nickname=%s&mac=%s&usertoken=%s&md5=%s&payexpanddata=%s&sdkver=%s&usertype=%s%s",
                goodPrice,
                goodmultiple,
                Zs4GameData.getInstance().getAppId(),
                Helper.isNull(Zs4GameData.getInstance().getServId()) ? "" : Zs4GameData.getInstance().getServId(),
                Helper.isNull(Zs4GameData.getInstance().getPlayerName()) ? "" : Zs4GameData.getInstance().getPlayerName(),
                Helper.isNull(Zs4GameData.getInstance().getPlayerId()) ? "" : Zs4GameData.getInstance().getPlayerId(),
                Helper.isNull(Zs4GameData.getInstance().getServName()) ? "" : Zs4GameData.getInstance().getServName(),
                Helper.isNull(Zs4GameData.getInstance().getUserId()) ? "" : Zs4GameData.getInstance().getUserId(),
                Helper.isNull(Zs4GameData.getInstance().getNickName()) ? "" : Zs4GameData.getInstance().getNickName(),
                ActivityHelper.getMacAddress(),
                Helper.isNull(Zs4GameData.getInstance().getToken()) ? "" : Zs4GameData.getInstance().getToken(),
                createMD5(),
                Helper.isNull(Zs4GameData.getInstance().getPayExpandData()) ? "" : Zs4GameData.getInstance().getPayExpandData(),
                Extra.VERSION,
                Helper.isNull(Zs4GameData.getInstance().getLoginType()) ? "" : Zs4GameData.getInstance().getLoginType(),
                ParamsHelper.getsUserAgentForWeb()
        );
        Log.e("pay"," payExpandData is ua is "+ua);
//        String postData = String.format("ua=%s&ua1=%s", JsonHelper.simpleEncode(ua), ParamsHelper.getUserAgent1());
//        LogUtil.e("UA++===========",ua);
        String postData = String.format("ua=%s", EncryptHelper.encryptByAES(ua));//, ParamsHelper.getUserAgent1());
        this.getWebView().postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));

    }


    /**
     * 生成md5校验码
     *
     * @return
     */
    private String createMD5() {
        // 加连成字符串后做MD
        String result = String.format("%d%s%s%s%s%s",
                Zs4GameData.getInstance().getAppId(),
                Helper.isNull(Zs4GameData.getInstance().getPlayerId()) ? "" : Zs4GameData.getInstance().getPlayerId(),
                Helper.isNull(Zs4GameData.getInstance().getServId()) ? "" : Zs4GameData.getInstance().getServId(),
                Helper.isNull(Zs4GameData.getInstance().getUserId()) ? "" : Zs4GameData.getInstance().getUserId(),
                Helper.isNull(Zs4GameData.getInstance().getToken()) ? "" : Zs4GameData.getInstance().getToken(),
                Zs4GameData.getInstance().getAppKey()
        );
        result = EncryptHelper.md5(result);
        return result;
    }


    @Override
    protected WebViewClient createWebViewClient() {
        WebViewClient webViewClient = new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.d(TAG, "shouldOverrideUrlLoading: " + url);
                if (url.endsWith(".apk")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url.startsWith("tel:")) {
//                    doCallPhone(url);
                    return true;
                } else if (url.startsWith("mqqwpa:")) {
                    // 判断qq-apk是否存在
                    if (ProjectHelper.checkApkExist(Zs4GameVoucherActivity.this, "com.tencent.mobileqq")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } else {
                        ActivityHelper.showToast("请先下载并安装QQ客户端");
                    }
                    return true;
                }

                if (url.contains(Extra.URL.SDKGAME_HOST_SELECT)) {
                    getWebView().loadUrl(url, getHeader());
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                LogUtil.d(TAG, "onPageStarted:" + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                LogUtil.d(TAG, "onPageFinished:" + url);
                super.onPageFinished(view, url);
                HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.DISMISSPROCESS);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                LogUtil.d(TAG,
                        String.format(
                                "onReceivedError:errorCode=%d, description=%s, failingUrl=%s",
                                errorCode, description, failingUrl));
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        };
        return webViewClient;
    }


    @Override
    protected void refreshWebView() {
        this.loadVoucher();
    }


    /**
     * 取得当前时间戳
     *
     * @return
     */
    private String getTimestamp() {
        return Helper.getUnixDate();
    }


    /**
     * function: 关闭进度框
     *
     * @ author: aXiBa 2014-1-8 下午5:02:59
     */
    public void closeProgress() {
        try {
            if (mProgress != null) {
                mProgress.dismiss();
                mProgress = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    ///////////////////////////////////////////////////////////////////////////
    // 网页支付
    ///////////////////////////////////////////////////////////////////////////

    /**
     * function: 发送支付完成广播
     *
     * @param orderid
     * @param payType
     * @ author: aXiBa 2014-1-8 下午5:09:03
     */
    private void sendPayCompleteBroadcast(String orderid, int payType) {

        Bundle bundle = new Bundle();
        bundle.putString(Zs4GameBase.KEY_ORDER_CODE, orderid);

        // 从菜单
        if (Extra.FLAG_MENU.equals(flag) || Extra.FLAG_MANUAL_MENU.equals(flag)) {
            ActivityHelper.sendBroadcast(Zs4GameBase.getPackageName().concat(Extra.ACTIONKEY.MESSAGE_POSTFIX), Zs4GameCode.PAYCOMPLETE, payType, this, bundle);
        }
        // 独立模块调用
        else {
            ActivityHelper.sendBroadcast(flag, Zs4GameCode.PAYCOMPLETE, payType, this, bundle);
        }
    }


    ///////////////////////////////////////////////////////////////////////////
    // 快捷支付
    ///////////////////////////////////////////////////////////////////////////

    // 快捷支付消息处理
    CommonHandle securePayHandler = new CommonHandle(Zs4GameVoucherActivity.this,
            new HandleMessage() {

                @Override
                public void doHandleMessage(final Message msg) {
                    // 请求订单信息

                    if (Extra.MessageKey.REQUEST_ORDERINFO == msg.what) {
                        requestOrderInfo(msg.arg1, (String) msg.obj, "", "");
                    } else if (Extra.MessageKey.REQUEST_WXORDERINFO == msg.what) {
//                        requestWXOrderInfo(msg.arg1, (String) msg.obj, "", "");
                    } else if (Extra.MessageKey.REQUEST_WXPAY == msg.what) {
//                        doWXPay((WXOrderResultEntity) msg.obj);
                    } else if (Extra.MessageKey.GOTO_VOUCHER_AGAIN == msg.what) {
//                        refreshWebView();
                    }else if (Extra.MessageKey.REQUEST_XZ_ORDER_SIGN == msg.what) {
                        requestXZSign();
                    }
                }
            });


    /**
     * function: 载入网页充值结果
     *
     * @param orderid
     * @param result
     * @param errormsg
     * @ author: aXiBa 2013-5-13 下午2:12:40
     */
    private void loadWebViewVoucherResult(String orderid, String result, String errormsg) {
        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWPROCESS_CANCANCEL);

        // 发送请求
        String url = String.format("%s?timestamp=%s&orderid=%s&result=%s&errormsg=%s",
                Extra.URL.VOUCHER_NNB_RESULT_API,
                this.getTimestamp(),
                orderid,
                result,
                errormsg
        );
//        this.getWebView().destroy();
        this.getWebView().loadUrl(url, getHeader());
    }

    /**
     * 去到显示支付结果
     *
     * @param success
     * @param desc
     */
    private void gotoShowPayResult(int success, String desc) {
        Intent intent = new Intent(this, Zs4GameVoucherResultActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(Extra.INTENTKEY.INTENT_TYPE, success);
        bundle.putString(Extra.INTENTKEY.BACKSENDMESSAGE, desc);
        bundle.putString(Extra.INTENTKEY.FLAG, flag);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();

    }


    /**
     * function: 支付宝快捷支付：请求订单信息
     *
     * @ author: aXiBa 2013-4-25 下午4:53:13
     */
    private void requestOrderInfo(final int flag, String goods_id, final String extra, final String payType) {

        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWPROCESS);
        String OrderUrl = "";


        LogUtil.e("============", "pay_type=" + pay_type);

        String url = String.format("%s?timestamp=%s&app_id=%d",
                Extra.URL.ORDERINFO_API,
                    this.getTimestamp(),
                    Zs4GameData.getInstance().getAppId());


//        LogUtil.e("============","url="+url);
//        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE,url);
        ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();

        String ua = String.format("payamount=%s&goodmultiple=%s&goodsid=%s&cp_order_id=%s&app_id=%d&role_id=%s&role_name=%s" +
                        "&area_server_id=%s&area_server_name=%s&user_id=%s&nickname=%s&mac=%s" +
                        "&usertoken=%s&md5=%s&payexpanddata=%s&sdkver=%s&usertype=%s&xzpaytype=%s%s",
                goodPrice,
                goodmultiple,
                pay_goods_id,//goods_id,
                pay_cp_order_id,
                Zs4GameData.getInstance().getAppId(),
                Helper.isNull(Zs4GameData.getInstance().getPlayerId()) ? "" : Zs4GameData.getInstance().getPlayerId(),
                Helper.isNull(Zs4GameData.getInstance().getPlayerName()) ? "" : Zs4GameData.getInstance().getPlayerName(),
                Helper.isNull(Zs4GameData.getInstance().getServId()) ? "" : Zs4GameData.getInstance().getServId(),
                Helper.isNull(Zs4GameData.getInstance().getServName()) ? "" : Zs4GameData.getInstance().getServName(),
                Helper.isNull(Zs4GameData.getInstance().getUserId()) ? "" : Zs4GameData.getInstance().getUserId(),
                Helper.isNull(Zs4GameData.getInstance().getNickName()) ? "" : Zs4GameData.getInstance().getNickName(),
                ActivityHelper.getMacAddress(),
                Helper.isNull(Zs4GameData.getInstance().getToken()) ? "" : Zs4GameData.getInstance().getToken(),
                createMD5(),
                Helper.isNull(Zs4GameData.getInstance().getPayExpandData()) ? "" : Zs4GameData.getInstance().getPayExpandData(),
                Extra.VERSION,
                Helper.isNull(Zs4GameData.getInstance().getLoginType()) ? "" : Zs4GameData.getInstance().getLoginType(),
                payType,
                ParamsHelper.getsUserAgentForWeb()

        );
        LogUtil.e("UA===========1", ua);
        paramsList.add(new BasicNameValuePair("ua", EncryptHelper.encryptByAES(ua)));

        new EventHandler2Post(
                url,
                paramsList,
                ParamsHelper.getUserAgent1(),
                new ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {
//					Log.e(TAG, "请求订单信息结果：" + result);

                        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.DISMISSPROCESS);

                        OrderResultEntity entity = new OrderResultEntity(result);
//                        LogUtil.e("=====订单号：",result.toString());
//                        Toast.makeText(Zs4GameVoucherActivity.this,result.toString(),Toast.LENGTH_LONG).show();
                        // 判断验证出错
                        if ("1".equals(entity.getErrcode())) {
                            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, entity.getMessage());
                        } else if (Helper.isEmpty(entity.getOrderid())) {
                            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_error")));
                        } else {
                            if (!entity.getSign().equals(md5OrderID(entity))) {
                                HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")));
                            } else{
                                LogUtil.e("订单正确：","订单正确，请求支付宝，虽然你没有参数");
                                HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SECUREPAY, entity);
                            }
                        }
                    }

                    @Override
                    public void doExceptionHandler() {

                        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.DISMISSPROCESS);
                        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_error")));
                    }
                });

    }


    private String md5OrderID(OrderResultEntity entity) {

        String before_md5 = Zs4GameData.getInstance().getAppId() + entity.getOrderid()
                + entity.getGoodsfee() + Zs4GameData.getInstance().getUserId()
                + Zs4GameData.getInstance().getToken() + Zs4GameData.getInstance().getAppKey();

        String sign = EncryptHelper.md5(before_md5);
//        LogUtil.e("请求订单数据问题：", entity.getSign() + "\n加密前getAppId：" + Zs4GameData.getInstance().getAppId() + "\ngetOrderid." + entity.getOrderid()
//                + "\ngetGoodsfee." + entity.getGoodsfee() + "\nNNB_DISCOUNT." + NNB_DISCOUNT + "\ngetUserId." + Zs4GameData.getInstance().getUserId()
//                + "\ngetToken." + Zs4GameData.getInstance().getToken() + "\ngetAppKey."
//                + Zs4GameData.getInstance().getAppKey() + "\nbefore_md5." + before_md5 + "\n加密后：" + sign);
        return sign;
    }


    @Override
    protected int getLeftBtnType() {
        if (Extra.FLAG_MENU.equals(flag) || Extra.FLAG_MANUAL_MENU.equals(flag)) {
            return TYPE_LEFTBTN_BACKTOMENU;
        } else if (Extra.BOOLEAN_TRUE.equals(backSendMsg)) {
            return TYPE_LEFTBTN_BACKTOGAME;
        } else {
            return TYPE_LEFTBTN_BACK;
        }
    }


 

    @Override
    protected void onDestroy() {

        if (this.getWebView() != null) {
            ViewGroup parent = (ViewGroup) this.getWebView().getParent();
            if (parent != null) {
                parent.removeView(this.getWebView());
            }
            this.getWebView().removeAllViews();
            this.getWebView().destroy();
        }
        super.onDestroy();
    }

    /**
     * 现在支付第一步
     * 服务端返回参数，客户端进行写入并获取待签名字符串
     *
     * @param entity
     */
    private void doXZPay(XZOrderResultEntity entity, String type) {
        if (Helper.isNull(entity.getXzappid()) || Helper.isEmpty(entity.getXzappid())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":xzappid");
        } else if (Helper.isNull(entity.getMhtOrderNo()) || Helper.isEmpty(entity.getMhtOrderNo())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":mhtOrderNo");
        } else if (Helper.isNull(entity.getMhtOrderName()) || Helper.isEmpty(entity.getMhtOrderName())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":mhtOrderName");
        } else if (Helper.isNull(entity.getMhtOrderType()) || Helper.isEmpty(entity.getMhtOrderType())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":mhtOrderType");
        } else if (Helper.isNull(entity.getMhtCurrencyType()) || Helper.isEmpty(entity.getMhtCurrencyType())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":mhtOrderDetail");
        } else if (Helper.isNull(entity.getMhtOrderDetail()) || Helper.isEmpty(entity.getMhtOrderDetail())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":timestamp");
        } else if (Helper.isNull(entity.getMhtOrderAmt()) || Helper.isEmpty(entity.getMhtOrderAmt())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":mhtOrderAmt");
        } else if (Helper.isNull(entity.getNotifyUrl()) || Helper.isEmpty(entity.getNotifyUrl())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":notifyUrl");
        } else if (Helper.isNull(entity.getMhtCharset()) || Helper.isEmpty(entity.getMhtCharset())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":mhtCharset");
        } else if (Helper.isNull(entity.getMhtSignType()) || Helper.isEmpty(entity.getMhtSignType())) {
            mLoadingDialog.dismiss();
            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":mhtSignType");
        } else {

            if (pay_type.equals(Extra.INTENTKEY.GAME_TPYE)) {
                mPreSign.appId = entity.getXzappid();
                mPreSign.mhtOrderNo = entity.getMhtOrderNo();
                mPreSign.mhtOrderName = entity.getMhtOrderName();
                mPreSign.mhtOrderAmt = entity.getMhtOrderAmt();
                mPreSign.mhtOrderDetail = entity.getMhtOrderDetail();
                mPreSign.mhtOrderStartTime = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
                mPreSign.notifyUrl = entity.getNotifyUrl();
                mPreSign.mhtOrderType = entity.getMhtOrderType();
                mPreSign.mhtCurrencyType = entity.getMhtCurrencyType();
                mPreSign.mhtOrderTimeOut = "3600";
                mPreSign.mhtCharset = entity.getMhtCharset();
                mPreSign.payChannelType = type;
                mPreSign.consumerId = Zs4GameData.getInstance().getUserId();
                mPreSign.consumerName = Zs4GameData.getInstance().getLastLoginedUserInfo().getLoginname();
                mPreSign.mhtLimitPay = null;
                String msg = mPreSign.generatePreSignMessage();
                if (Helper.isNotNull(msg) && Helper.isNotEmpty(msg)) {
                    HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.REQUEST_XZ_ORDER_SIGN);
                } else {
                    mLoadingDialog.dismiss();
                    HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("zs4gamestring_hint_requestorderinfo_data_error")) + ":SignMessage=" + msg);
                }
            }
        }
    }

    /**
     * 请求现在支付的签名
     */
    private void requestXZSign() {
        String url = String.format("%s?timestamp=%s&app_id=%d",
                Extra.URL.XZ_WX_SIGN_API,
                this.getTimestamp(),
                Zs4GameData.getInstance().getAppId());
        ArrayList<NameValuePair> paramsList = new ArrayList<NameValuePair>();

        LogUtil.e("现在支付签名前", "==" + mPreSign.generatePreSignMessage());
        paramsList.add(new BasicNameValuePair("xzpresign", EncryptHelper.encryptByAES(mPreSign.generatePreSignMessage() + "&")));
        new EventHandler2Post(
                url,
                paramsList,
                ParamsHelper.getUserAgent1(),
                new ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {
                        final XzSignOrderResultEntity entity = new XzSignOrderResultEntity(result);
                        mLoadingDialog.dismiss();
                        if (entity.isSuccess()) {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {

                                    String requestMessage = mPreSign.generatePreSignMessage() + "&" + entity.getData();
                                    if (Helper.isNotEmpty(mPreSign.mhtReserved) && requestMessage.contains(mPreSign.mhtReserved))
                                        requestMessage = requestMessage.replace(mPreSign.mhtReserved, URLEncoder.encode(mPreSign.mhtReserved));
                                    mIpaynowplugin.setCustomLoading(mLoadingDialog).setCallResultReceiver(Zs4GameVoucherActivity.this)
                                            .pay(requestMessage);
                                    LogUtil.e("现在支付签名后", requestMessage);
                                    // 调用sdk方法
                                }
                            });
                        } else {
                            HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, entity.getDesc());
                        }
                    }

                    @Override
                    public void doExceptionHandler() {

                        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.DISMISSPROCESS);
                        HandlerUtil.sendMessage(securePayHandler, Extra.MessageKey.SHOWMESSAGE, getString(ActivityHelper.getStringResId("niustring_hint_requestorderinfo_error")));
                    }
                });

    }

    @Override
    public void onIpaynowTransResult(ResponseParams responseParams) {
        String respCode = responseParams.respCode;
        String errorCode = responseParams.errorCode;
        String errorMsg = responseParams.respMsg;
        StringBuilder temp = new StringBuilder();
        if (respCode.equals("00")) {
            sendPayCompleteBroadcast(pay_cp_order_id, Zs4GameCode.PAYTYPE_SECURE);
            gotoShowPayResult(Extra.JSONReturnResult.SUCCESS, "");
        }else if (respCode.equals("02")) {
            sendPayCompleteBroadcast(pay_cp_order_id, Zs4GameCode.PAYSECURE_CANCEL);
            gotoShowPayResult(Extra.JSONReturnResult.FAIL, "交易状态:用户取消");
        } else{
            sendPayCompleteBroadcast(pay_cp_order_id, Zs4GameCode.PAYSECURE_FAIL);
            gotoShowPayResult(Extra.JSONReturnResult.FAIL, "原因:"+errorCode+"-" + errorMsg);
        }


//        if (respCode.equals("00")) {
//            sendPayCompleteBroadcast(pay_cp_order_id, NiuniuGameCode.PAYTYPE_SECURE);
//            gotoShoePayResult(Extra.JSONReturnResult.SUCCESS, "");
//        } else if (respCode.equals("02")) {
//            temp.append("交易状态:取消");
//        } else if (respCode.equals("01")) {
//            temp.append("交易状态:失败").append("\n").append("错误码:").append(errorCode).append("原因:" + errorMsg);
//        } else if (respCode.equals("03")) {
//            temp.append("交易状态:未知").append("\n").append("原因:" + errorMsg);
//        } else {
//            temp.append("respCode=").append(respCode).append("\n").append("respMsg=").append(errorMsg);
//        }
//        Log.e("交易结果", temp.toString());
//        Toast.makeText(this, "onIpaynowTransResult:" + temp.toString(), Toast.LENGTH_LONG).show();
    }


}
